#include <mex.h>
#include "sgmin.h"

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[0])
{
	int NY, NX, MX, NW0, MW0;

	NY = mxGetM(prhs[0]);

	NX = mxGetN(prhs[1]);
	MX = mxGetM(prhs[1]);

	NW0 = mxGetN(prhs[5]);
	MW0 = mxGetM(prhs[5]);

#if 0
	mexPrintf("NY: %d.\n",NY);
	mexPrintf("MX: %d, NX: %d.\n",MX,NX);
	mexPrintf("MW0: %d, NW0: %d.\n",MW0,NW0);
#endif

	plhs[0] = mxCreateDoubleMatrix(165,2,mxREAL); //WX
	plhs[1] = mxCreateDoubleMatrix(13,2,mxREAL); //W

	double *W, *WX; //Init val --> W0.

	WX = mxGetPr(plhs[0]);
	W = mxGetPr(plhs[1]);

	double *Y, *X, *W0;

	Y = mxGetPr(prhs[0]);
	X = mxGetPr(prhs[1]);
	W0 = mxGetPr(prhs[5]);

	int method, morph, dim;

	double *pOpts;
	pOpts = mxGetPr(prhs[2]);	method = pOpts[0];
	pOpts = mxGetPr(prhs[3]);	morph = pOpts[0];
	pOpts = mxGetPr(prhs[4]);	dim = pOpts[0];

	vector<double> bY (NY); double *pbY = &bY(0);
	matrix<double> bX (MX,NX); double *pbX = &bX(0,0);
	matrix<double> bW0 (13,2); double *pbW0 = &bW0(0,0);

	memcpy(pbY,Y,NY*sizeof(double));

	int k=0;
	for(int i=0;i<NX;i++){
		for(int j=0;j<MX;j++){
			bX(j,i) = X[k]; k++; //Lee columna y asigna fila!
		}
	}

	k=0;
	for(int i=0;i<NW0;i++){
		for(int j=0;j<MW0;j++){
			bW0(j,i) = W0[k]; k++; //Lee columna y asigna fila!
		}
	}

#if 0
	for(int i=0;i<NY;i++) mexPrintf("%f \n",bY(i));
	mexPrintf("\n\n");
	for(int i=0;i<MX;i++){ 
		for(int j=0;j<NX;j++){
			mexPrintf("%f ",bX(i,j));
		}
		mexPrintf("\n");
	}
	mexPrintf("\n\n");
	for(int i=0;i<MW0;i++){ 
		for(int j=0;j<NW0;j++){
			mexPrintf("%f ",bW0(i,j));
		}
		mexPrintf("\n");
	}
#endif

#if 0
	bW0(0,0) =  0.6846; bW0(0,1)= 0.4885;
	bW0(1,0) = -0.0031; bW0(1,1)= 0.0177;
  bW0(2,0) = -0.0114; bW0(2,1)=  0.0683;
  bW0(3,0) = -0.0159; bW0(3,1)= 0.0834;
  bW0(4,0) = -0.0450; bW0(4,1)=  0.0293;
  bW0(5,0) =  0.6598; bW0(5,1)= -0.1108;
  bW0(6,0) =  0.2534; bW0(6,1)= -0.6559;
  bW0(7,0) =  0.1124; bW0(7,1)= -0.4245;
  bW0(8,0) =  0.0866; bW0(8,1)= -0.2726;
  bW0(9,0) =  0.0906; bW0(9,1)= -0.1872;
  bW0(10,0) =  0.0302; bW0(10,1)= -0.1177;
  bW0(11,0) = -0.0057; bW0(11,1)= -0.0484;
  bW0(12,0) =  0.0019; bW0(12,1)= -0.0181;
#endif	

#if 1
	resldr<double> res = ldr(bY,bX,method,morph,dim,bW0);

	k=0;
	for(int i=0;i<2;i++){
		for(int j=0;j<165;j++){
			WX[k] = res.WX(j,i); k++; //Lee columna y asigna fila!
		}
	}

	k=0;
	for(int i=0;i<2;i++){
		for(int j=0;j<13;j++){
			W[k] = res.W(j,i); k++; //Lee columna y asigna fila!
		}
	}

#endif
}

